<?php
namespace app\index\controller;
use think\Controller;
use app\index\common;
use think\Db;
use think\Request;
use app\index\controller\Log\InsertLog as IL;
use app\index\controller\Product;
use app\index\controller\Order;
use app\index\controller\Log\OperationLog as OL;

class Nursing extends Controller
{
    
    /**
     * 2018-05-10
     * 曹振威
     * 生成护理编号
     */
    
    public function nursing_code($product_id = 0){
        // 操作的用户id
        $batchcode = date('Ym').$this->user_id.$product_id.date('d').date('His');
        $date = array('code'=>666,'msg'=>'护理编号获取成功','data'=>$batchcode);
        return $date;
    }
    /**
     * 2018-04-23 开发日期
     * 曹振威 开发人
     * 添加护理单
     */
    public function add_nursing(Product $product,Request $R) {
        $post = $R->post();
        $procurement_status = 0;
            Db::startTrans();
            try{
                if(empty($post['id'])){
                    if(!array_key_exists('product_id',$post)){  // 非现有订单
                        if(isset($post['product_sn'])){
                            $product_info = Db::table('product')->where('product_sn',$post['product_sn'])->field('id')->select();
                            if($product_info){
                                $date = array('code'=>20080,'msg'=>'产品货号已存在，请重新输入产品货号或不输入，系统自动生成。','data'=>'');
                                exit(json_encode($date));
                            } 
                        }
                        $product_insert = [
                            'system_id' => $this->system_id,
                            'business_id' => $this->business_id,
                            'store_id' => $this->store_id,
                            'staff_id' => $this->staff_id,
                            'systematics_id' => $post['systematics_id'],
                            'product_condition' => $post['product_condition'],
//                            'is_shelf' => 4,
                            'stock' => $post['nursing_num'],
                            'product_name' => $post['product_name'],
                            'product_sn' => $post['product_sn'],
                            'pic_url' => $post['cover_img'],
                            'is_own' => 1,
                            'product_state' => 17,
                            'createtine' => date('Y-m-d H:i:s'),
                        ];
                        $product_id = Db::table('product')->insertGetId($product_insert);
                        $procurement_status = 0;
                        $product_img = [
                            'product_id'=>$product_id,
                            'pic_url'=> $post['cover_img'],
                            'createtime'=> date('Y-m-d H:i:s')
                        ];
                        Db::table('productpic')->insert($product_img);
                    } else {
                        $product_info = $product->check_product($post['product_id']);
                        if($product_info['is_own'] == 1 && !$product_info['product_state'] == 18){
                             exit(json_encode(['code'=>20740,'msg'=>'客户护理产品还在护理中，不可再次添加护理','data'=>'']));
                        }
                        if($product_info['product_state'] != 2 && $product_info['product_state'] != 10){
                            exit(json_encode(['code'=>20725,'msg'=>'只有在库未售和待发货状态才可以护理','data'=>'']));
                        }
                        $product_id = $product_info['id'];
                        $product_info['procurement_status'] ? $procurement_status = $product_info['procurement_status'] : $procurement_status = 0;
                        $product_state = $product_info['product_state'];
                    }
                }else{
                    if(isset($post['product_id']) && !empty($post['product_id'])){
                        $product_id = $post['product_id'];
                    }else{
                        $product_order = Db::table('orders_info')->where(array('id'=>$post['id'],'state'=>0,'is_nursing'=>1))->field('product_id,procurement_status,product_name')->find();
                        if(!$product_order){
                            $product_order = Db::table('orders_info')->where(array('batchcode'=>$post['order_source'],'state'=>0))->field('product_id,procurement_status,product_name')->find();
                        }
                        $product_order['procurement_status'] ? $procurement_status = $product_order['procurement_status'] :$procurement_status = 0;
                        $product_id = $product_order['product_id'];
                        $product_info = $product->check_product($product_id);
                        $product_state = $product_info['product_state'];
                    }
                    $product_img = [
                        'pic_url'=> $post['cover_img'],
                        'createtime'=> date('Y-m-d H:i:s')
                    ];
                    Db::table('productpic')->insert($product_img);
                    $product_update = [
                        'systematics_id' => $post['systematics_id'],
                        'product_state' => 7, // 库存商品护理已售
                        'pic_url' => $post['cover_img'],
                        'createtine' => date('Y-m-d H:i:s'),
                    ];
                    Db::table('product')->where('id',$product_id)->update($product_update);
                }
                if(!$post['nursing_sn']){
                    $date = array('code'=>20087,'msg'=>'护理编号不能为空','data'=>'');
                    exit(json_encode($date));
                }
                $order_insert = [
                    'system_id' => $this->system_id,
                    'business_id' => $this->business_id,
                    'type' => 0,
                    'batchcode' => $post['nursing_sn'],
//                    'status' => 2,
                    'createtime' => date('Y-m-d H:i:s'),
                    'last_time' => date('Y-m-d H:i:s'),
                ];
                isset($post['shipping_method']) ? $order_insert['shipping_code'] = $post['shipping_method'] : FALSE;
                isset($post['pay_method']) ? $order_insert['pay_code'] = $post['pay_method'] : FALSE;
                isset($post['nursing_fee']) ? $post['nursing_fee'] : $post['nursing_fee'] = 0;
                isset($post['nursing_num']) ? $post['nursing_num'] : $post['nursing_num'] = 1;
                $order_insert['total_price'] = (float)$post['nursing_fee']*(float)$post['nursing_num'];
                isset($post['order_source']) ? $order_insert['order_source'] = $post['order_source'] : FALSE;
            $order_info_insert = [
                'system_id' => $this->system_id,
                'business_id' => $this->business_id,
                'store_id' => $this->store_id,
                'product_id' => $product_id,
                'batchcode' => $post['nursing_sn'],
                'info_batchcode' => $post['nursing_sn'].$product_id,
                'quantity' => $post['nursing_num'],
                'product_name' => $post['product_name'],
                'createtime' => date('Y-m-d H:i:s'),
                'nursing_cost' => $post['nursing_cost'],
                'nursing_fee' => $post['nursing_fee'],
                'nursing_income' => (float)$post['nursing_fee']-(float)$post['nursing_cost'],
                'nursing_remark' => $post['nursing_remark'],
                'customer_name' => $post['customer'],
                'is_nursing' => 1,
                'procurement_status' => $procurement_status,
                'last_time' => date('Y-m-d H:i:s'),
            ];
            if($post['urgent_remark']){
                $order_insert['urgent_remark'] = $post['urgent_remark'];
                $order_insert['is_urgent'] = 1;
                $order_info_insert['urgent_remark'] = $post['urgent_remark'];
                $order_info_insert['is_urgent'] = 1;
            }elseif(($post['urgent'] == 1 && !$post['urgent_remark']) || $post['urgent'] == 0){
                $order_insert['is_urgent'] = $post['urgent'];
                $order_info_insert['is_urgent'] = $post['urgent'];
            }
            $order_info_insert['parts'] = $post['parts'];
            $order_info_insert['remark'] = $post['remark'];
            $order = new Order();
            $customer_id = $order->check_customer($post['phone']);
            $order_info_insert['user_id'] = $customer_id['id'];
            $order_insert['user_id'] = $customer_id['id'];
            $row_orders_info = '';
            $product_info = $product->check_product($product_id);
            if($product_info['is_own'] == 0){
                if($product_info['product_state'] != 2 && $product_info['product_state'] != 10){
                    exit(json_encode(['code'=>20725,'msg'=>'只有在库未售和待发货状态才可以护理','data'=>'']));
                }elseif($product_info['product_state'] == 17){
                    $product_state = 17;
                }else{
                    $product_state = 7;
                }
            }else{
                $product_state = 17;
            }
            $additional = Db::table('product')->where('id',$product_id)->value('additional');
            isset($post['nursing_cost']) ? $product_fee = (float)$additional + (float)$post['nursing_cost'] : $product_fee = $additional;
            if(empty($post['id'])){ // 添加
                $a = '添加';
                $order_insert['status'] = 2;
                $order_info_insert['status'] = 2;
                isset($post['cover_img']) ? $order_insert['cover'] = $post['cover_img'] : FALSE;
                $row_order = Db::table('orders')->insertGetId($order_insert);
                $row_orders_info = Db::table('orders_info')->insertGetId($order_info_insert);
                Db::table('product')->where('id',$product_id)->update(array('product_state'=>$product_state,'additional'=>$product_fee));
            } elseif(isset($post['id']) && !empty($post['order_source']) && $this->get_order($post['order_source']) && $this->get_order($post['nursing_sn'])){ // 订单添加
                $a = '订单添加';
                isset($post['cover_img']) ? $order_insert['cover'] = $post['cover_img'] : FALSE;
//                $status = Db::table('orders')->where('batchcode',$post['order_source'])->value('status');
                $order_insert['status'] = 2;
                $order_info_insert['status'] = 2;
                $order_info_insert['batchcode'] = $post['nursing_sn'];
                $order_info_insert['info_batchcode'] = $post['nursing_sn'].$product_id;
                $order_insert['batchcode'] = $post['nursing_sn'];
                $row_order = Db::table('orders')->insertGetId($order_insert);
                $row_orders_info = Db::table('orders_info')->insertGetId($order_info_insert);
                Db::table('product')->where('id',$product_id)->update(array('product_state'=>$product_state,'additional'=>$product_fee));
            }elseif(isset($post['id']) && isset($post['nursing_sn']) && !$this->get_order($post['nursing_sn'])) { // 编辑
                $a = '编辑';
                Db::table('orders_info')->where('id',$post['id'])->update($order_info_insert);
                Db::table('orders')->where('batchcode',$post['nursing_sn'])->update($order_insert);
                $row_order = Db::table('orders')->where('batchcode',$post['nursing_sn'])->value('id');
                $row_orders_info = $post['id'];
                Db::table('product')->where('id',$product_id)->setField('additional',$product_fee);
            }
            if(!$row_orders_info){
                $date = array('code'=>29995,'msg'=>'护理订单操作失败','data'=>array('order_id'=>$post['id']));
                exit(json_encode($date));
            }
            // 提交事务
            Db::commit();
            $date = array('code'=>666,'msg'=>'添加/编辑护理订单成功','data'=>array('order_id'=>$row_orders_info,'a'=>$a));
            OL::insert([
                'user_id'=> $this->user_id,
                'module' => 'orders', 
                'module_id' => $row_order, 
                'operation_type' => 2,  
                'operation_content' => json_encode(['orders' => Db::table('orders')->where(['id'=>$row_order])->find(),
                    'orders_info' => Db::table('orders_info')->where(['id'=>$row_orders_info])->find(),
                    'product' => Db::table('product')->where(['id'=>$product_id])->find(),
                    ])
            ]);
            } catch (Exception $e) {
                // 回滚事务
                Db::rollback();
                $date = array('code'=>20041,'msg'=>'添加/编辑护理订单失败'.$e,'data'=>'');
            }
        return $date;
    }
    
    public function get_order($order_sn){
        $row_nursing = Db::table('orders_info')
                ->where(array('batchcode'=>$order_sn,'is_nursing'=>1))
                ->find();
        if(!$row_nursing){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 2018-04-23 开发日期
     * 曹振威 开发人
     * 护理单列表
     */
    public function nursing_list($action = '') {
        $where_arr = array();
        $where_arr['o.state'] = 0;
        $where_arr['or.state'] = 0;
        $where_arr['o.is_nursing'] = 1;
        $this->system_id ? $where_arr['o.system_id'] = $this->system_id : false;
        $this->business_id ? $where_arr['o.business_id'] = $this->business_id : false;
        $this->store_id ? $where_arr['o.store_id'] = $this->store_id : false;
        input('title') ? $where_arr['o.nursing_remark'] = ['LIKE','%'.input('title').'%'] : false;
        input('product_sn') ? $where_arr['p.product_sn'] = ['LIKE','%'.input('product_sn').'%'] : false;
        input('nursing_sn') ? $where_arr['o.batchcode'] = ['LIKE','%'.input('nursing_sn').'%'] : false;
        input('phone') ? $where_arr['u.phone'] = ['LIKE','%'.input('phone').'%'] : false;
        input('customer') ? $where_arr['o.customer_name'] = ['LIKE','%'.input('customer').'%'] : false;
        input('order_source') ? $where_arr['or.order_source'] = ['LIKE','%'.input('order_source').'%'] : false;
        $pay_method = input('pay_method');
        $settlement_status = input('settlement_status');
        $nursing_status = input('nursing_status');
        if(isset($pay_method) && $pay_method != ''){
            $where_arr['or.pay_code'] = $pay_method;
        }
        if(isset($settlement_status) && $settlement_status != ''){
            $where_arr['o.is_settlement'] = $settlement_status;
        }
        if(isset($nursing_status) && $nursing_status != ''){
            $where_arr['o.status'] = $nursing_status;
        }
        $begin_time = input('begin_time');
        $end_time = input('end_time');
        if($begin_time && empty($end_time)){
            $end_time = date('Y-m-d H:i:s');
            $where_arr['o.createtime'] = ['EGT',"$begin_time"];
        }elseif (empty($begin_time) && $end_time) {
            $where_arr['o.createtime'] = ['ELT',date('Y-m-d',strtotime("$end_time +1 day"))];
        } elseif($begin_time && $end_time) {
            $end_time = date('Y-m-d',strtotime("$end_time +1 day"));
            $where_arr['o.createtime'] = ['between',"$begin_time,$end_time"];
        }
        $field = 'o.id,o.quantity,o.batchcode,o.nursing_fee,o.nursing_remark,'
                . 'o.customer_name,u.phone,or.cover pic_url,p.product_condition,pf.value product_condition_value,o.product_name,'
                . 'p.product_sn,o.status,o.createtime,or.is_urgent,o.is_settlement,o.settlement_time,'
                . 'p.systematics_id,p.product_state,pst.value product_state_value,nc.value status_value';
        if(empty($action)){
            $row = Db::table('orders_info')->alias('o')
                    ->join('orders or','o.batchcode = or.batchcode','LEFT')
                    ->join('product p','o.product_id = p.id','LEFT')
                    ->join('product_fineness pf','p.product_condition = pf.id', 'LEFT')
                    ->join('users u','o.user_id=u.id','LEFT')
//                    ->join('sales_condition sc','sc.id=o.status','LEFT')sc.value status_value,
                    ->join('product_state pst','pst.id = p.product_state', 'LEFT')
                    ->join('nursing_condition nc','nc.id = or.status','LEFT')
                    ->where($where_arr)->order('o.createtime','desc')
                    ->field($field)
                    ->paginate()->toArray();
            $product = new Product();
            foreach ($row['data'] as $nkey => $nvalue) {
                $systematics_arr = $product->set_product_name($nvalue['systematics_id']);
                if(!$systematics_arr['data']){
                    $row['data'][$nkey]['pre_name'] = '';
                }else{
                    $row['data'][$nkey]['pre_name'] = $systematics_arr['data'];
                }
            }
            $date = array('code'=>666,'msg'=>'护理订单列表获取成功','data'=>$row);
            IL::insert('log', [
                'user_id'=>$this->user_id,
                'operation_user'=> $this->user['name'],
                'operation_name'=>'查看', 
                'operation_content'=>'查看护理订单列表',
                'ip'=> Request()->ip(),
                'createtime'=>date('Y-m-d H:i:s'),
                'state'=>1
            ]);
        }elseif($action = 'nursing_excel'){
            $date = Db::table('orders_info')->alias('o')
                    ->join('orders or','o.batchcode = or.batchcode','LEFT')
                    ->join('product p','o.product_id = p.id','LEFT')
                    ->join('users u','o.user_id=u.id','LEFT')
                    ->where($where_arr)
                    ->field($field)
                    ->paginate();
        } 
       return $date;
    }
    
    /**
     * 2018-04-23 开发日期
     * 曹振威 开发人
     * 删除护理单
     */
    public function nursing_delete() {
        $id = input('id');
        if(!$id){
            $date = array('code'=>20021,'msg'=>'要删除的订单编号不能为空','data'=>'');
            exit(json_encode($date));
        }else{
            $order_ids = explode(",",$id);
            $nursings = Db::table('orders')
                                ->whereIn('batchcode', $order_ids)
                                ->select();  
            if(empty($nursings)){
                $date = array('code'=>20096,'msg'=>'该订单不存在','data'=>'');
                exit(json_encode($date));
            } 
            foreach ($nursings as $nursing) {
                $nursing_order = Db::table('orders_info')
                                    ->where(['batchcode' =>$nursing['batchcode'] ])
                                    ->find();
                if(empty($nursing_order)){
                    $date = array('code'=>20097,'msg'=>'该订单不存在','data'=>'');
                    exit(json_encode($date));
                }elseif($nursing_order['is_nursing'] != 1){
                    $date = array('code'=>20098,'msg'=>'该订单非护理订单','data'=>'');
                    exit(json_encode($date));
                }elseif($nursing_order['is_settlement'] != 1){
                    $date = array('code'=>20999,'msg'=>'该护理订单未结算，不可删除','data'=>'');
                    exit(json_encode($date));
                }
            }
             $row = Db::table('orders_info')
                    ->whereIn('batchcode', $order_ids)
                    ->update(['state'=>1]); 
            $row_order = Db::table('orders')->whereIn('batchcode',$order_ids)->update(['state'=>1]);
            $row_id = Db::table('orders_info')
                    ->whereIn('batchcode', $order_ids)
                    ->value('id');
            $row_order_id = Db::table('orders')->whereIn('batchcode',$order_ids)->value('id');
        }
        
        if($row && $row_order){
            $date = array('code'=>666,'msg'=>'护理订单删除成功','data'=>'');
            OL::insert([
                'user_id'=> $this->user_id,
                'module' => 'orders', 
                'module_id' => $row_order_id, 
                'operation_type' => 4,  
                'operation_content' => json_encode(['orders' => Db::table('orders')->where(['id'=>$row_order_id])->find(),
                    'orders_info' => Db::table('orders_info')->where(['id'=>$row_id])->find(),
                    ])
            ]);
        }else{
            $date = array('code'=>20043,'msg'=>'护理订单删除失败','data'=>'');
        }
        return $date;
    }
    
    /**
     * 2018-04-23 开发日期
     * 曹振威 开发人
     * 护理单导出
     */
    public function nursing_excel() {
        $data = $this->nursing_list('nursing_excel');      //  数据
         $key = [
            '订单类型','订单号','产品编号','产品名称','产品现价','成本价','同行价','订单总价','返佣总额','运费总额','订单状态','所需积分','获得积分','单个产品总佣金','产品数量','支付时间'
        ];
        $keyname = array('type','batchcode','product_id','product_name','price','cost_price','peer_price','total_price','total_rebate','total_fare','status','pequired_points','earn_points','total_commission','quantity','pay_reatetime');
        
        $styleArray = ['font' => ['bold' => true]];        // 样式  如第一行全部加粗
        common::output_excel($key, $data, $keyname, '护理订单列表',$styleArray);
    }
    
    /** 
     * 护理订单结算
     * @return string
     */
    public function nursing_settlement(){
        $id = input('id');
        if(!$id){
            exit(json_encode(array('code'=>20021,'msg'=>'结算的订单号不能为空','data'=>'')));
        }
        $where['id'] = $id;
        $this->business_id ? $where['business_id'] = $this->business_id : exit(json_encode(array('code'=>20021,'msg'=>'非法操作','data'=>'')));
        $this->store_id ? $where['store_id'] = $this->store_id : FALSE;
        $where['state'] = 0;
        $nursing_up = [
            'is_settlement' => 1,
            'status' => 3,
            'settlement_time' => date('Y-m-d H:i:s'),
            'last_time' => date('Y-m-d H:i:s'),
        ];
        Db::table('orders_info')->where($where)->update($nursing_up);
        $settlement_time = Db::table('orders_info')->where($where)->field('id,settlement_time,batchcode,product_id')->find();
        Db::table('orders')->where('batchcode',$settlement_time['batchcode'])->setField('last_time',date('Y-m-d H:i:s'));
        $product_status = Db::table('product')->where('id',$settlement_time['product_id'])->value('product_state');
        if($product_status == 17){
            Db::table('product')->where('id',$settlement_time['product_id'])->setField('product_state',18);
        }elseif($product_status == 3){
            Db::table('product')->where('id',$settlement_time['product_id'])->setField('product_state',2);
        }elseif($product_status == 7){
            $orders_row = Db::table('orders_info')->where('product_id',$settlement_time['product_id'])->field('status,is_prepay');
            if($orders_row['status'] == 2 && $orders_row['is_prepay'] == 0){  // 存在销售订单 且  是待发货状态  且  全款支付
                Db::table('product')->where('id',$settlement_time['product_id'])->setField('product_state',10);
            }elseif($orders_row['is_prepay'] == 1){
                Db::table('product')->where('id',$settlement_time['product_id'])->setField('product_state',6);
            }
        }
        $orders = Db::table('orders')->where('batchcode',$settlement_time['batchcode'])->value('id');
        $date = array('code'=>666,'msg'=>'护理订单结算成功','data'=>array('orders_id'=>$id,'settlement_time'=>$settlement_time['settlement_time']));
        OL::insert([
                'user_id'=> $this->user_id,
                'module' => 'orders', 
                'module_id' => $orders, 
                'operation_type' => 4,  
                'operation_content' => json_encode([
                    'product' => Db::table('product')->where(['id'=>$settlement_time['product_id']])->find(),
                    'orders' => Db::table('orders')->where(['id'=>$orders])->find(),
                    'orders_info' => Db::table('orders_info')->where(['id'=>$settlement_time['id']])->find(),
                    
                    ])
            ]);
        return $date;
    }
}

